/**
 * Created by Dell on 2017/5/23.
 */
'use strict';
const pg = require('../lib/pgClient');
const log = require('log4js').getLogger('../models/feedback');
const add_sql1 = 'INSERT INTO feedback (userid, mobile, content, createtime, status, picture) VALUES ($1, $2, $3, $4, $5, $6)';//添加反馈
exports.add = function(params, callback){
    pg.query(add_sql1, params, function(err, result){//添加反馈
        if(err){
            callback (err, null);//报错
        }else if(result.rowCoun == 0){
            callback (err, 'null');//添加失败
        }else{
            callback (err, result);//添加成功
        }
    });
};
/**
 * 后台多条件查询反馈列表
 * @param params
 * @param args
 * @param callback
 */
exports.list = function(params, args, callback){
    let sql = 'SELECT f.*, u.username, u.mobile FROM feedback f,users u WHERE u.id = f.userid';
    let number = 1;
    if(args.keyword){
        sql += ' AND (f.content like $'+number+' OR u.username like $'+number+' OR u.mobile like $'+number+')';
        number ++;
    }
    sql += ' ORDER BY f.createtime DESC LIMIT $'+number+' OFFSET $'+(number+1);
    pg.query(sql, params, function(err, result){//直行sql语句
        if(err){
            callback (err, null);//执行查询操作报错
        }else {
            callback (err, result);//返回结果
        }
    });
};

/**
 * 后台多条件查询反馈列表数据统计
 * @param params
 * @param args
 * @param callback
 */
exports.count = function(params, args, callback){
    let sql = 'SELECT count(*) FROM feedback f,users u WHERE u.id = f.userid';
    let number = 1;
    if(args.keyword){
        sql += ' AND (f.content like $'+number+' OR u.username like $'+number+' OR u.mobile like $'+number+')';
        number ++;
    }
    pg.query(sql, params, function(err, result){//直行sql语句
        if(err){
            callback (err, null);//执行查询操作报错
        }else {
            callback (err, result);//返回结果
        }
    });
};

/**
 * 后台批量删除用户反馈
 * @param args
 * @param callback
 */
exports.remove = function(args, callback){
    let ids = args.ids;//ids 是数组
    let theids = "'"+ids.join("','")+"'";//将数组ids整理成字符串
    const sql1 = 'SELECT * FROM feedback WHERE id in ('+theids+')';//是否有日志
    const sql2 = 'DELETE FROM feedback WHERE id in ('+theids+')';//删除日志
    pg.query(sql1, [], function(err, result){//执行sql语句
        if(err){
            callback (err, null);//查找报错
        }else if (result.rowCount == 0){
            callback (err, 'null');//没有日志记录
        }else{
            pg.query(sql2, [], function(err, result){//执行删除操作
                if(err){
                    callback (err, null);
                }else if(result.rowCount == 0){
                    callback (err, 'fail');//报错
                }else {
                    callback (err, result);
                }
            })
        }
    })
};